import React from 'react';
import { Link } from 'react-router-dom';
import { Button,MessageBox} from 'element-react';
import { Steps } from 'element-react';
import Top from '../../top/index.js';
import Nav from '../../nav/index.js';
import axios from 'axios';
import util from '../../../assets/js/util.js';
import './trackSend.css';

let posiIco = require('../../../assets/img/posi.png');
let posiIco1 = require('../../../assets/img/posi1.png');
let BMap = window.BMap//取出window中的BMap对象
let BMAP_ANIMATION_DROP = window.BMAP_ANIMATION_DROP;//取出window中的BMap对象
let BMAP_STATUS_SUCCESS = window.BMAP_STATUS_SUCCESS;//取出window中的BMap对象
let map;
   
class Track extends React.Component {
    constructor(props){
        super(props);
        this.state={
            trackData:{}, //服务亭到工厂轨迹数据
            geographyList:[
                // {houseName: "桂花园北区", houseY: "32.973906", houseX: "117.359167", factoryY: "32.965319", factoryX: "117.339349",factoryName:'桑德两网融合专业回收示范基地',"packageName": "桑德两网融合回收示范基地","packageX": "117.396061","packageY": "32.944766"},
                // {houseName: "桂花园南区", houseY: "32.973313", houseX: "117.358749", factoryY: "32.965319",factoryX: "117.339349",factoryName:'桑德两网融合专业回收示范基地',"packageName": "桑德两网融合回收示范基地","packageX": "117.396061","packageY": "32.944766"},
                // {houseName: "荷花园一二期", houseY: "32.978298", houseX: "117.38528", factoryY: "32.965319",factoryX: "117.339349",factoryName:'桑德两网融合专业回收示范基地',"packageName": "桑德两网融合回收示范基地","packageX": "117.396061","packageY": "32.944766"},
                // {houseName: "槐花园A区", houseY: "32.982457", houseX: "117.407276", factoryY: "32.965319",factoryX: "117.339349",factoryName:'桑德两网融合专业回收示范基地',"packageName": "桑德两网融合回收示范基地","packageX": "117.396061","packageY": "32.944766"}
            ]
        }
    }

    componentDidMount() {
        var orderNum = this.props.match.params.orderNum;
        // 获取服务亭收货轨迹坐标
        this.getRecycleTrack(orderNum);
        // 获取服务亭收货轨迹
        this.getRecycleTrack2(orderNum);
    }

    // 获取服务亭收货轨迹
    getRecycleTrack2(orderNum){
        var params = new URLSearchParams();
        params.append('orderNum',orderNum);

        axios.post('/count/userfactory/recyclefactory', params).then((data) => {
            console.log(data)

            let trackData = data.data.recycleOrderRecycle;
            this.setState({
                trackData: trackData
            })

        }).catch((e) => {
            console.log(e)
        })
    }

    //获取服务亭收货轨迹坐标
    getRecycleTrack(orderNum) {
        var params = new URLSearchParams();
        params.append('orderNum',orderNum);

        axios.post('/count/userfactory/packagecheck', params).then((data) => {
            console.log(data);
            if(data.data.code == 0){
                this.setState({
                   geographyList: data.data.data
                })

                let geographyList = this.state.geographyList

                if(!geographyList) return //alert('没有获取到轨迹数据');

                let centerP = {}
                let endP = {}
                let packName
                let factoryName
                let houseName = []
                let arrayList = []

                geographyList.forEach((item, index) => {
                    let P = new BMap.Point(item.houseX, item.houseY) //服务亭
                    centerP = new BMap.Point(item.packageX, item.packageY) //分拣中心
                    if(item.factoryX && item.factoryY){
                        endP =  new BMap.Point(item.factoryX, item.factoryY) //工厂
                    }
                    arrayList.push(P) //把map点放到数组中
                    houseName.push(item.houseName) //把名称放到数组中
                    packName = item.packageName
                    if(item.factoryName){
                        factoryName = item.factoryName
                    }
                })

                arrayList.push(centerP)
                if(JSON.stringify(endP) !== "{}"){
                    arrayList.push(endP)
                }
                houseName.push(packName)
                if(factoryName){
                    houseName.push(factoryName)
                }

                setTimeout(()=>{
                    //初始化地图
                    this.initMap(arrayList)
                    //显示轨迹
                    this.showPoly(arrayList, houseName)
                },100)
            }else if(data.data.code == -111){
                MessageBox.alert(data.data.msg);
            }else{
                this.props.history.push('/login')
            }
            
        }).catch((e) => {
            console.log(e)
        })
    }

    //初始化地图
    initMap(data){
        // 创建Map实例
        map = new BMap.Map("allmap", {enableMapClick: true})
        let x = data[0].lng
        let y = data[0].lat
        map.centerAndZoom(new BMap.Point(x, y), 14) //中心点 蚌埠 117.395639, 32.921375 根据第一个确定中心点
        map.enableScrollWheelZoom(true) //滚轮放大缩小
        map.setMapStyle({style:'grayscale'}) //设置地图主题
        //map.enableScrollWheelZoom(true);  //启用滚轮放大缩小
    }

    //显示坐标点
    showPoly(pointList, houseName) {
        //循环显示点对象
        for (let c = 0; c < pointList.length; c ++) {
            //设置定位图标
            var myPosIcon = new BMap.Icon(posiIco, new BMap.Size(19, 25))
            var marker = new BMap.Marker(pointList[c], { icon: myPosIcon })
            map.addOverlay(marker); //画出marker
            marker.setAnimation(BMAP_ANIMATION_DROP) //设置marker进场动画
            //将途经点按顺序添加到地图上  显示该点的名称

            //设置起点和路径点 服务亭、分拣中心
            if(c !== pointList.length - 1){
                let start
                if(c === 0) {
                    start = '起点：'
                } else{
                    start = ''
                }

                var label = new BMap.Label(start + houseName[c], {
                    offset: new BMap.Size(20, -2) //偏移量
                });
            }else{
                //最后一个点是终点 工厂
                var label = new BMap.Label('终点：' + houseName[c], {
                    offset: new BMap.Size(20, -2) //偏移量
                });
            }
            label.setStyle({
                color: '#fff',
                backgroundColor: 'rgba(0, 0, 0, 0.6)',
                'border-radius': '10px',
                border: 0,
                padding: '4px 5px',

            })
            marker.setLabel(label)
        }

        var group = Math.floor(pointList.length / 11)
        var mode = pointList.length % 11;

        var driving = new BMap.DrivingRoute(map, {
            onSearchComplete: function (results) {
                if (driving.getStatus() === BMAP_STATUS_SUCCESS) {
                    var plan = driving.getResults().getPlan(0);
                    var num = plan.getNumRoutes();
                    //alert("plan.num ：" + num);
                    for (var j = 0; j < num; j++) {
                        var pts = plan.getRoute(j).getPath(); //通过驾车实例，获得一系列点的数组
                        var polyline = new BMap.Polyline(pts,  {strokeColor: '#f83d3d', strokeWeight:6, strokeOpacity:0.8});
                        map.addOverlay(polyline);
                    }
                }
            }
        })
        for (var i = 0; i < group; i++) {
            var waypoints = pointList.slice(i * 11 + 1, (i + 1) * 11);
            //注意这里的终点如果是11的倍数的时候，数组可是取不到最后一位的，所以要注意终点-1 **
            driving.search(pointList[i * 11], pointList[(i + 1) * 11 - 1], {
                waypoints: waypoints
            }) //waypoints表示途经点
        }
        if (mode !== 0) {
            var waypoints = pointList.slice(group * 11, pointList.length - 1); //多出的一段单独进行search
            driving.search(pointList[group * 11], pointList[pointList.length - 1], {
                waypoints: waypoints
            })
        }
    }

    render() {
        return ( 
            <div className="main_serviceHouseSend">
              <Top/>
              <Nav serviceReceive="active"/>
           
               <div className="container_track">
                    <div className="track-nav">
                        <span className="track"><h3>服务亭收货明细 > 轨迹</h3></span>
                        {/*<span type = "info" className="return">
                            //<Link to="../serviceHouseReceive">返回</Link>
                        </span>*/}
                    </div>
                    <div className="progress">
                        <div className="roww">
                            <div className="item">
                                <img src={require('../../../assets/img/right-circle.png')} />
                                <p className="desc">{this.state.trackData.userName}</p>
                                <p className="desc">{this.state.trackData.userMobile}</p>
                                <p className="desc">{this.state.trackData.address}</p>
                                <p className="desc">No.{this.state.trackData.orderNum}</p>
                            </div>
                            <div className="item">
                                <img src={require('../../../assets/img/right-circle.png')} />
                                <p className="desc">{this.state.trackData.houseName}</p>
                                <p className="desc">No.{this.state.trackData.orderNum}</p>
                                <p className="desc">创建时间：{this.state.trackData.recycleOrderCtime?util.getDateTime(this.state.trackData.recycleOrderCtime):'--'}</p>
                            </div>
                            {
                                this.state.trackData.flowOrderNum?
                                <div className="item">
                                    <img src={require('../../../assets/img/right-circle.png')} />
                                    <p className="desc">No.{this.state.trackData.flowOrderNum}</p>
                                    <p className="desc">车牌号：{this.state.trackData.carrierCarnum}</p>
                                    <p className="desc">司机名称：{this.state.trackData.shipMentCarrierName}</p>
                                    <p className="desc">发货时间：{this.state.trackData.sendTime?util.getDateTime(this.state.trackData.sendTime):'--'}</p>
                                    <p className="desc">交货时间：{this.state.trackData.arriveTime?util.getDateTime(this.state.trackData.arriveTime):'--'}</p>
                                </div>
                                :''
                            }
                            {
                                this.state.trackData.flowOrderNum?
                                <div className="item">
                                    <img src={require('../../../assets/img/right-circle.png')} />
                                    <p className="desc">No.{this.state.trackData.flowOrderNum}</p>
                                    <p className="desc">{this.state.trackData.houseName} - {this.state.trackData.substationName}</p>
                                </div>
                                :''
                            }
                            {
                                this.state.trackData.arteryOrderNum?
                                <div className="item">
                                    <img src={require('../../../assets/img/right-circle.png')} />
                                    <p className="desc">No.{this.state.trackData.arteryOrderNum}</p>
                                    <p className="desc">车牌号：{this.state.trackData.otcarNum}</p>
                                    <p className="desc">司机名称：{this.state.trackData.carrierName}</p>
                                    <p className="desc">公司：{this.state.trackData.carOwnFirm}</p>
                                    <p className="desc">发货时间：{this.state.trackData.sendTransportTime?util.getDateTime(this.state.trackData.sendTransportTime):'--'}</p>
                                    <p className="desc">交货时间：{this.state.trackData.transportArriveTime?util.getDateTime(this.state.trackData.transportArriveTime):'--'}</p>
                                </div>
                                :''
                            }
                            {
                                this.state.trackData.arteryOrderNum?
                                <div className="item">
                                    <img src={require('../../../assets/img/right-circle.png')} />
                                    <p className="desc">No.{this.state.trackData.arteryOrderNum}</p>
                                    <p className="desc">{this.state.trackData.substationName} - {this.state.trackData.recycleFactoryName}</p>
                                </div>
                                :''
                            }
                        </div>
                    </div>
                    <div className="allmap-container">
                        <div id='allmap' className="route_map" style={{width:'98%',height:'100%'}}>
                            地图加载失败，请检查网络或刷新网页...
                        </div>
                    </div>
               </div>
            
            </div>
        );
    }
}

export default Track